package sg.edu.nus.iss.billing.gui;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import sg.edu.nus.iss.billing.controller.UserController;
import sg.edu.nus.iss.billing.exception.ControllerException;
import sg.edu.nus.iss.billing.exception.ValidationException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.gui.component.ValidateJTextField;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;
import sg.edu.nus.iss.billing.privilege.AdminRole;
import sg.edu.nus.iss.billing.privilege.AgentRole;
import sg.edu.nus.iss.billing.privilege.Role;
import sg.edu.nus.iss.billing.privilege.User;
import sg.edu.nus.iss.billing.validation.ValidationRule;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class AddEditUserPanel extends DefaultFunctionPanel  {
	
	private static final long serialVersionUID = 1L;
	private JLabel usernameLbl;
	private JLabel passwordLbl;
	private JLabel roleLbl;
	private ValidateJTextField usernameTxt;
	private ValidateJTextField passwordTxt;
	private ValidateJTextField confirmPwdTxt;
	private JComboBox roleComboBox;
	private JButton addButton;
	private JButton resetButton;
	private JButton cancelButton;
	private JButton updateButton;
	private UserController userController;
	private UpdateUserPanel _parent;
	
	public AddEditUserPanel(){
		init("");
		userController = new UserController();
	}
	
	public AddEditUserPanel(String username, UpdateUserPanel parent) throws ControllerException {
		this();
		this._parent = parent;
		if (username != null) {
			User userObj = null;
			try {
				userObj = userController.getUserByName(username,true);
			} catch (ControllerException e) {
				throw e;
			}
			populateUserInfo(userObj);
		}
	}
	
	private JPanel populateEditActionsButton() {
		JPanel buttonPanel = new JPanel();
		FlowLayout thisLayout = new FlowLayout();
		thisLayout.setAlignment(FlowLayout.CENTER);
		buttonPanel.setLayout(thisLayout);

		updateButton = new JButton();
		updateButton.setText(MessageKeyManager.getMessage("button.update"));
		updateButton.addActionListener(new OnUpdateUserClick());
		
		cancelButton = new JButton();
		cancelButton.setText(MessageKeyManager.getMessage("button.cancel"));
		cancelButton.addActionListener(new OnCancelUserClick());
		
		buttonPanel.add(updateButton);
		buttonPanel.add(cancelButton);
		
		return buttonPanel;
	}
	
	private void populateUserInfo(User userObj) throws ControllerException {
		usernameTxt.setText(userObj.getUsername());
		usernameTxt.setEditable(false);
		passwordTxt.setText(userObj.getPassword());
		if (userObj.getRole() instanceof AdminRole) {
			roleComboBox.setSelectedIndex(1);
		} else {
			roleComboBox.setSelectedIndex(0);
		}
		refreshActionButtonPanel(null);
		_parent.refreshActionButtonPanel(populateEditActionsButton());
	}
	
	private class OnResetUserClick implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			usernameTxt.setText("");
			passwordTxt.setText("");
		}
	}
	
	private class OnCancelUserClick implements ActionListener {
	    public void actionPerformed(ActionEvent e) {
	        _parent.refreshBottomPanel(_parent.createBottomPanel());
          _parent.refreshActionButtonPanel();
	    }
	}
	
	private class OnUpdateUserClick implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				String username = usernameTxt.getValidatedText();
				User userObj = userController.getUserByName(username);
				String password = passwordTxt.getValidatedText();
				Role role = null;
				if (roleComboBox.getSelectedIndex() == 0) {
					role = new AgentRole(); 
				} else if (roleComboBox.getSelectedIndex() == 1) {
					role = new AdminRole();
				}
				userObj.setPassword(password);
				userObj.setRole(role);
				userController.editUser(userObj);
				JOptionPane.showMessageDialog(null, MessageKeyManager.getMessage("msg.editUserSuccess"), MessageKeyManager.getMessage("msg.title.success"), JOptionPane.INFORMATION_MESSAGE);
			} catch (ValidationException ex) {
				ErrorDialog.showValidationErrorMessageDialog(ex);
			} catch (ControllerException ex) {
				ErrorDialog.showControllerErrorMessageDialog(ex);
			} catch (Exception ex) {
				ErrorDialog.showUnhandledErrorMessageDialog(ex);
			}
			new OnCancelUserClick().actionPerformed(null);
		}
	}
	
	private class OnAddUserClick implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				String username = usernameTxt.getValidatedText();
				String password = passwordTxt.getValidatedText();
				Role role = null;
				if (roleComboBox.getSelectedIndex() == 0) {
					role = new AgentRole(); 
				} else if (roleComboBox.getSelectedIndex() == 1) {
					role = new AdminRole();
				}
				userController.addUser(username, password, role);
				JOptionPane.showMessageDialog(null, MessageKeyManager.getMessage("msg.addUserSuccess"), MessageKeyManager.getMessage("msg.title.success"), JOptionPane.INFORMATION_MESSAGE);
			    new OnResetUserClick().actionPerformed(null);
			} catch (ValidationException ex) {
				ErrorDialog.showValidationErrorMessageDialog(ex);
			} catch (ControllerException ex) {
				ErrorDialog.showControllerErrorMessageDialog(ex);
			} catch (Exception ex) {
				ErrorDialog.showUnhandledErrorMessageDialog(ex);
			}
		}
	}
	
	public JPanel createTopPanel() {
		return null;
	}
	
	public JPanel createActionButtonsPanel() {
		JPanel buttonPanel = new JPanel();
		FlowLayout thisLayout = new FlowLayout();
		thisLayout.setAlignment(FlowLayout.CENTER);
		buttonPanel.setLayout(thisLayout);

		addButton = new JButton();
		addButton.setText(MessageKeyManager.getMessage("button.add"));
		addButton.addActionListener(new OnAddUserClick());
		
		resetButton = new JButton();
		resetButton.setText(MessageKeyManager.getMessage("button.reset"));
		resetButton.addActionListener(new OnResetUserClick());
		
		buttonPanel.add(addButton);
		buttonPanel.add(resetButton);
		
		return buttonPanel;
	}
	
	public JPanel createBottomPanel() {
		JPanel addUserPanel = new JPanel();
		GridBagLayout thisLayout = new GridBagLayout();
		//setPreferredSize(new Dimension(800, 600));
		thisLayout.rowWeights = new double[] {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1};
		thisLayout.rowHeights = new int[] {7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
		thisLayout.columnWeights = new double[] {0.1, 0.6, 0.3};
		thisLayout.columnWidths = new int[] {7, 7, 7};

		addUserPanel.setLayout(thisLayout);
		
		usernameLbl = new JLabel(MessageKeyManager.getMessage("label.username"));
		addUserPanel.add(usernameLbl, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(10, 10, 0, 0), 0, 0));

		usernameTxt = new ValidateJTextField(MessageKeyManager.getMessage("label.username"), ValidationRule.NOT_NULL);
		addUserPanel.add(usernameTxt, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 0, 0, 0), 0, 0));

		passwordLbl = new JLabel(MessageKeyManager.getMessage("label.password"));
		addUserPanel.add(passwordLbl, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(10, 10, 0, 0), 0, 0));
		
		passwordTxt = new ValidateJTextField(MessageKeyManager.getMessage("label.password"), ValidationRule.NOT_NULL);
		addUserPanel.add(passwordTxt, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 0, 0, 0), 0, 0));

		roleLbl = new JLabel(MessageKeyManager.getMessage("label.role"));
		addUserPanel.add(roleLbl, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(10, 10, 0, 0), 0, 0));

		roleComboBox = new JComboBox();
		ComboBoxModel defaultRoleModel = 
			new DefaultComboBoxModel(
					new String[] {"Call Agent", "Authorised Admin"});
		addUserPanel.add(roleComboBox, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(10, 0, 0, 0), 0, 0));
		roleComboBox.setModel(defaultRoleModel);
		
		return addUserPanel;
	}
	
}
